/*
 * Created: Author: Aléx Carvalho / Date: Mar 13, 2015
 * 
 * Changed: $Author: ac280593@gmail.com $ / $Date: 2015-06-11 01:31:49 -0300 (Thu, 11 Jun 2015) $
 */
package com.cpm.view.zk.tree.structure;

import com.cpm.ServiceLocator;
import com.cpm.entities.Folder;
import com.cpm.entities.Indicator;
import com.cpm.entities.Node;
import com.cpm.entities.Node_;
import com.cpm.entities.StrategicPlan;
import static com.cpm.entities.types.Family.STRATEGIC_PLAN;
import com.cpm.repository.Filter;
import com.cpm.view.zk.tree.DefaultTreeNode;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class StructureLoader implements Serializable {

    private Collection<Folder> folders;
    private Collection<Indicator> indicators;

    public void loadStructure(DefaultTreeNode<Node> root, StrategicPlan plan) {

        Filter filter = ServiceLocator.getFilter().andEquals(Node_.strategicPlan, plan);
        
        folders = filter.getResultList(Folder.class);

        indicators = filter.getResultList(Indicator.class);

        folders.stream().filter((f) -> (f.getParentFamily() == STRATEGIC_PLAN)).forEach(f -> getChilds(f, root));

    }

    private void getChilds(Node data, DefaultTreeNode<Node> treeNode) {
        Predicate<Node> predicate = (Node t) -> t.getParentId().equals(data.getId()) && t.getParentFamily() == data.getFamily();

        List<Node> nodes = indicators.stream().filter(predicate).collect(Collectors.toList());

        nodes.addAll(folders.stream().filter(predicate).collect(Collectors.toList()));

        nodes.sort((Node i1, Node i2) -> {
            return i1.getPosition().compareTo(i2.getPosition());
        });
//
//        map.put(data.getParentFamily() +""+ data.getId(), nodes);

        DefaultTreeNode childNode = new DefaultTreeNode(data);
        treeNode.add(childNode);

        nodes.forEach(n -> getChilds(n, childNode));
    }
}
